package com.bwie.record.generator;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

public class RandomIDGenerator {
    private static final String[] AREA_CODES = {"110000", "120000", "130000", "110000", "110100" , "110101" , "110102" , "110103" , "110104" , "110105" , "110106" , "110107" , "110108" , "110109" , "110111" , "110112" , "110113" , "110200"}; // 省略了部分区域码
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
    private static final Random RANDOM = new Random();

    public static String generateRandomID() {
        // 随机选择地区码
        String areaCode = AREA_CODES[RANDOM.nextInt(AREA_CODES.length)];

        // 随机生成出生日期码（假设范围为1950年到当前年份）
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 1950 + RANDOM.nextInt(calendar.get(Calendar.YEAR) - 1950 + 1));
        calendar.set(Calendar.DAY_OF_YEAR, 1 + RANDOM.nextInt(calendar.getActualMaximum(Calendar.DAY_OF_YEAR)));
        String birthDateCode = DATE_FORMAT.format(calendar.getTime());

        // 随机生成顺序码（前两位）
        String sequenceCode = String.format("%02d", RANDOM.nextInt(99));

        // 计算校验码
        String idWithoutCheckDigit = areaCode + birthDateCode + sequenceCode;
        char checkDigit = calculateCheckDigit(idWithoutCheckDigit);

        // 拼接完整的身份证号码
        return idWithoutCheckDigit + checkDigit;
    }

    private static char calculateCheckDigit(String idWithoutCheckDigit) {
        int sum = 0;
        int[] weights = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] checkDigits = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};

        for (int i = 0; i < idWithoutCheckDigit.length(); i++) {
            sum += (idWithoutCheckDigit.charAt(i) - '0') * weights[i];
        }

        int remainder = sum % 11;
        return checkDigits[remainder];
    }
}
